package com.epam.tcs.dao.hibernate.impl;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;

import com.epam.tcs.dao.factory.StudentDAO;
import com.epam.tcs.dao.hibernate.ConnectionFactory;
import com.epam.tcs.dao.hibernate.entities.Student;

public class StudentDAOHibernateImpl extends ElementDAOHibernateImpl<Student>
		implements StudentDAO {

	public StudentDAOHibernateImpl(Class<?> objType) {
		this.objType = objType;
	}

	@Override
	public Student getElement(long id) {
		Session session = ConnectionFactory.getOrInitSession();
		Student student = (Student) session.load(objType, id);
		Hibernate.initialize(student.getGroup().getStudents());
		session.close();
		return student;
	}

	@Override
	public List<Student> getAllElements() {
		Session session = ConnectionFactory.getOrInitSession();
		List<Student> students = (List<Student>) session.createQuery(
				"from " + objType.getName()).list();

		for (Student student : students) {
			Hibernate.initialize(student.getGroup().getStudents());
		}

		session.close();
		return students;
	}
	 
	@Override
	public List<Student> getRangeElements(int start, int count) {
			Session session = ConnectionFactory.getOrInitSession();
			Query query = session.createQuery("from " + objType.getName());
			query.setFirstResult(start);
			query.setMaxResults(count);
			List<Student> students = (List<Student>) query.list();

			
			for (Student student : students) {
				Hibernate.initialize(student.getGroup().getStudents());
			}

			session.close();
			return students;
	}
	@Override
	public int getTotalElements() {
		Session session = ConnectionFactory.getOrInitSession();
		Query query = session.createQuery("from " + objType.getName());
		int count = query.list().size();
		session.close();
		return count;
	}

}
